//
//  ChangePasswordViewController.m
//  DataStatistics
//
//  Created by oilklenze on 16/1/28.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "ChangePasswordViewController.h"
#import "LoginVC.h"
#import "MBProgressHUD.h"
#import "MoreViewController.h"
#import "isPhoneNumber.h"
#import "UITextField+LolitaText.h"
#import "ChangePasswordModel.h"
#import "ChangePasswordViewModel.h"


@interface ChangePasswordViewController () <UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField         * oldPassword;
@property (strong, nonatomic) IBOutlet UITextField         * newpasswordssss;
@property (strong, nonatomic) IBOutlet UITextField         * surePassword;
@property (strong, nonatomic) NSMutableDictionary          * parameter;

@property (strong, nonatomic) IBOutlet UINavigationItem *changePassNav;
@property (strong, nonatomic) IBOutlet UIBarButtonItem *changePassCancel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *statusConstraint;
@property (weak, nonatomic) IBOutlet UIButton *OK;


@end

@implementation ChangePasswordViewController

- (void)viewDidLoad
{
    
    self.view.backgroundColor = RGB(33, 38, 44, 1);
    self.oldPassword.delegate     = self;
    self.newpasswordssss.delegate = self;
    self.surePassword.delegate    = self;
    self.surePassword.tag = 2;
    
    self.changePassNav.title = NSLocalizedString(@"CpvcLead_change", @"修改密码");
    // 设置navigationbar的半透明效果
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    
    [self.navigationController setNavigationBarHidden:NO];
    self.navigationController.navigationBar.barTintColor = RGB(7, 13, 20, 1.0);

    [self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor]}];
    
    [super viewDidLoad];

    
    [UITextField addYTYanKTextFielStyle1:self.oldPassword withString:NSLocalizedString(@"CpvcLead_0", @"旧密码")];
    [UITextField addYTYanKTextFielStyle1:self.newpasswordssss withString:NSLocalizedString(@"CpvcLead_1", @"输入范围")];
    [UITextField addYTYanKTextFielStyle1:self.surePassword withString:NSLocalizedString(@"Lead_5", @"确认")];

    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [self.oldPassword becomeFirstResponder];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
    [self.view endEditing:YES];
}

#pragma mark- TextField 代理

/**
 *  点击键盘确定
 */
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
    if (textField.tag == 2) {
        [self OK:nil];
    }
    if (textField == self.oldPassword) {
        [self.newpasswordssss becomeFirstResponder];
    }
    if (textField == self.newpasswordssss) {
        [self.surePassword becomeFirstResponder];
        self.surePassword.returnKeyType = UIReturnKeyDone;
    }
    return YES;
}




- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    return newString.length<13;
}



- (IBAction)cancal:(UIBarButtonItem*)sender
{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


/**
 *  确定
 */
- (IBAction)OK:(id)sender
{
    NSString *oldPassword, *newPassword, *confirmpassword;
    oldPassword     = self.oldPassword.text;
    newPassword     = self.newpasswordssss.text;
    confirmpassword = self.surePassword.text;

    NSString *str;
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSString *pass = [defaults objectForKey:MDC_PASSWORD_VLUE];

    if (![oldPassword isEqualToString:pass]){
        
        str  = NSLocalizedString(@"SvcLead_5",@"原密码不正确");
        
    }else if ([isPhoneNumber  illegalCharacter:confirmpassword] || [isPhoneNumber  illegalCharacter:newPassword]) {
        str  = NSLocalizedString(@"SvcLead_2",@"非法字符");
    }else if ([confirmpassword length] <6 && [newPassword length]<6) {
        str = NSLocalizedString(@"Lead_1",@"长度不合格");
    }else if ([confirmpassword isEqualToString:newPassword]) {
        [self.parameter setValue:oldPassword forKey:@"oldPwd"];
        [self.parameter setValue:newPassword forKey:@"newPwd"];
        [self dataRequestChangePassword];
        return;
    }else {
        str = NSLocalizedString(@"Tip_2",@"密码不一致");
    };
    [MBProgressHUD yty_showErrorWithTitle:nil detailsText:str toView:nil];
    
    
}

//发起请求
- (void)dataRequestChangePassword
{
    [ChangePasswordViewModel requestWithUrlForChangePassword:self andParam:self.parameter success:^(ChangePasswordModel *model) {
             NSString* string = [NSString stringWithFormat:@"%@", model.updateResult];
             [self showAlert:string];
    } failure:^(NSString *error) {
         [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
    }];
}


/** 修改密码 */
- (void)showAlert:(NSString*)retureData
{
    NSDictionary* dic = @{
                          @"0" :NSLocalizedString( @"CpvcTip0",nil),
                          @"1" :NSLocalizedString( @"CpvcTip1",nil),
                          @"2" :NSLocalizedString( @"CpvcTip2",nil),
                          @"3" :NSLocalizedString(@"CpvcTip3",nil),
                          @"4" :NSLocalizedString( @"CpvcTip1",nil),
                          @"5" :NSLocalizedString( @"CpvcTip3",nil)
                          };
    NSString* tis = dic[retureData];
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];

        if ([tis isEqualToString:@"密码修改成功！"])
            

        [MBProgressHUD showSuccess:tis];
        
        [self.view endEditing:YES];
        
        
    });

    if ([retureData isEqualToString:@"2"]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MoreViewController logout:self];
        });
    }
}



-(void)keyboardWasShown
{
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        
        [UIView animateWithDuration:0.24 animations:^{
            self.statusConstraint.constant = 240;
            CGRect btnFrame = self.OK.frame;
            btnFrame.origin.y -= 240;
            self.OK.frame = btnFrame;
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
            
        }];
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"667.0")) {
        
        [UIView animateWithDuration:0.24 animations:^{
            self.statusConstraint.constant = 280;
            CGRect btnFrame = self.OK.frame;
            btnFrame.origin.y -= 280;
            self.OK.frame = btnFrame;
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
            
        }];
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"736.0")) {
        [UIView animateWithDuration:0.24 animations:^{
            self.statusConstraint.constant = 300;
            CGRect btnFrame = self.OK.frame;
            btnFrame.origin.y -= 300;
            self.OK.frame = btnFrame;
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
        }];
    }
}

-(void)keyboardWillBeHidden
{
    
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        
        [UIView animateWithDuration:0.5 animations:^{
            self.statusConstraint.constant = 95;
            CGRect btnFrame = self.OK.frame;
            btnFrame.origin.y += 140;
            self.OK.frame = btnFrame;
            [[NSNotificationCenter defaultCenter] addObserver:self
             
                                                     selector:@selector(keyboardWasShown)
             
                                                         name:UIKeyboardWillShowNotification object:nil];
        }];
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"667.0")) {
        
        [UIView animateWithDuration:0.5 animations:^{
            self.statusConstraint.constant = 106;
            CGRect btnFrame = self.OK.frame;
            btnFrame.origin.y += 160;
            self.OK.frame = btnFrame;
            [[NSNotificationCenter defaultCenter] addObserver:self
             
                                                     selector:@selector(keyboardWasShown)
             
                                                         name:UIKeyboardWillShowNotification object:nil];
        }];
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"736.0")) {
        [UIView animateWithDuration:0.5 animations:^{
            self.statusConstraint.constant = 106;
            CGRect btnFrame = self.OK.frame;
            btnFrame.origin.y += 160;
            self.OK.frame = btnFrame;
            [[NSNotificationCenter defaultCenter] addObserver:self
             
                                                     selector:@selector(keyboardWasShown)
             
                                                         name:UIKeyboardWillShowNotification object:nil];
        }];
    }
}


- (NSMutableDictionary*)parameter
{
    if (!_parameter) {
        NSString  *str = MDC_USERCODE;
        _parameter = @{ @"user_id" : str};
       _parameter = [_parameter mutableCopy];
    }
    return _parameter;
}


@end
